package yxgf.oem.oemquotemgt.plugin.form;

import com.alibaba.nacos.common.utils.StringUtils;
import com.grapecity.documents.excel.S;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.field.events.AfterF7SelectEvent;
import kd.bos.form.field.events.AfterF7SelectListener;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import yxgf.oem.oemquotemgt.commons.constant.BillIdConstant;
import yxgf.oem.oemquotemgt.commons.constant.BillMsgConstant;
import yxgf.oem.oemquotemgt.commons.constant.NumConstant;
import yxgf.oem.oemquotemgt.commons.dto.PriceDto;
import yxgf.oem.oemquotemgt.commons.enums.BillMsgEnum;
import yxgf.oem.oemquotemgt.commons.enums.StockTypeEnum;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description： 营销配方插件
 * @version: v1.0
 * @author: Junit
 * @date: 2025/5/12
 */
public class MarketBillFormPlugIn extends AbstractFormPlugin implements BeforeF7SelectListener {
    private int time = 0;
    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        setDefStockType();
    }


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
    }


    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();
        boolean formulaListener;
        switch (fieldKey) {
            case BillIdConstant.MAT_FORMULA_CODE:
                formulaListener = true;
                DynamicObject formulaObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                buildMaterPriceDetail(formulaObj.getString(BillIdConstant.BILL_NUM), formulaListener);
                break;
            case BillIdConstant.MAT_DETAIL_CODE:
                formulaListener = false;
                DynamicObject detailObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                buildMaterPriceDetail(detailObj.getString(BillIdConstant.BILL_NUM), formulaListener);
                break;
            case BillIdConstant.BUS_DATE:
                setDefStockType();
                break;
            case BillIdConstant.PRODUCT_DETAIL_STD:
                DynamicObject proObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                buildProDetail(proObj.getString(BillIdConstant.BILL_NUM));
                break;
            default:
                break;
        }
    }

    /**
     * 构建原料明细
     *
     * @param materialCode
     * @param formulaListen
     */
    private void buildMaterPriceDetail(String materialCode, boolean formulaListen) {
        if(time != 0) return;

        if (!verifyPass()) {
            this.getView().showMessage(BillMsgConstant.SELECT_STOCK_ORG);
            return;
        }

        // 客户类型
        Object cusType = this.getModel().getValue("yxgf_cus_type");
        if (cusType == null) {
            delRowData(formulaListen);
            this.getView().showMessage(BillMsgConstant.SELECT_CUS_TYPE);
        } else {


            // 价格单据体数据集,存在则返回不添加，否则增加分录
            DynamicObjectCollection collection = getModel().getEntryEntity(BillIdConstant.MAT_PRICE_DETAIL);
            if (collection != null && collection.size() > 1) {
                boolean isExist = false;
                int repeat = 1;
                for (int index = 0; index < collection.size() - 1; index++) {
                    DynamicObject dynObj = (DynamicObject) this.getModel().getValue("yxgf_material_no", index - 1);
                    if (dynObj == null) {
                        addDataRow(collection, materialCode, formulaListen);
                    } else {
                        String yy = dynObj.getString("number");
                        if (StringUtils.equals(materialCode, dynObj.getString("number"))) {
                            isExist = true;
                            repeat += 1;
                        }
                    }
                }
                // 校验存在性，存在则删除
                if (!isExist && repeat == 1) {
                    addDataRow(collection, materialCode, formulaListen);
                } else {
                    // 测试
                    this.getModel().deleteEntryRow(BillIdConstant.MAT_PRICE_DETAIL, collection.size() - 1);
                }
            } else {
//                if(collection.size() == 1){
//                    DynamicObject dynObj = (DynamicObject) this.getModel().getValue("yxgf_material_no", 0);
//                    if(dynObj == null ||  checkDataRow(collection,materialCode,formulaListen) == false){
//                        addDataRow(collection,materialCode,formulaListen);
//                    }
//                }else {
//                    addDataRow(collection,materialCode,formulaListen);
//                }
                // 增加分录
                addDataRow(collection, materialCode, formulaListen);
            }
        }
        time += 1;
    }


    private boolean checkDataRow(DynamicObjectCollection collection, String materialCode, boolean formulaListen) {
        for (int index = 0; index < collection.size(); index++) {
            DynamicObject dynObj = (DynamicObject) this.getModel().getValue("yxgf_material_no", index);
            if (dynObj == null) {
                addDataRow(collection, materialCode, formulaListen);
            } else {
                String yy = dynObj.getString("number");
                if (StringUtils.equals(materialCode, dynObj.getString("number"))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 添加价格明细分录
     *
     * @param collection
     * @param materialCode
     * @param formulaListen
     */
    private void addDataRow(DynamicObjectCollection collection, String materialCode, boolean formulaListen) {
        int row = 0;
        if (formulaListen && collection.size() > 0) {
            Object detailObj = collection.get(0).get(BillIdConstant.MAT_DETAIL_CODE);
            if (detailObj != null) {
                row = this.getModel().createNewEntryRow(BillIdConstant.MAT_PRICE_DETAIL);
            }
            addRowData(row, collection, materialCode, formulaListen);
        } else {
            addRowData(row, collection, materialCode, formulaListen);
        }
    }

    /**
     * 设置价格行
     *
     * @param row
     * @param dos
     * @param materialCode
     * @param formulaListen
     */
    private void addRowData(int row, DynamicObjectCollection dos, String materialCode, boolean formulaListen) {
        QFilter qfilter = new QFilter("number", QCP.equals, materialCode);
        DynamicObject dynObj = QueryServiceHelper.queryOne("bd_material", "id", qfilter.toArray());

        if (!formulaListen) {
            if (dos.size() > 0) {
                setPriceInfo(dos.size() - 1, materialCode);
            }
        } else {
            getModel().setValue(BillIdConstant.MAT_DETAIL_CODE, dynObj.get("id"), row);
            setPriceInfo(row, materialCode);
        }
        getModel().updateEntryCache(dos);
    }

    /**
     * 价格处理
     *
     * @param index
     * @param materialCode
     */
    private void setPriceInfo(int index, String materialCode) {
        DynamicObject orgObj = (DynamicObject) this.getModel().getValue("yxgf_orgfield");
        if (orgObj != null) {
            String masterId = (String) orgObj.get("number");
            String stockType = (String) getModel().getValue("yxgf_kcjlx");

            CustomApiResult<PriceDto> apiResult = DispatchServiceHelper.invokeService("yxgf.oem.oemquotemgt.mservice.factory", "llj-quotemgt",
                    "IPriceService", "getPriceList", masterId, materialCode, stockType, "");
            PriceDto res = apiResult.getData();
            getModel().setValue("yxgf_mark_price", res.getForPrice(), index);
            getModel().setValue("yxgf_stock_price", res.getStockPrice(), index);

            getModel().setValue("yxgf_comp_price", res.getCompPrice(), index);
            getModel().setValue("yxgf_cwyljj_text", res.getFinancePrice(), index);
        } else {
            this.getView().showMessage(BillMsgConstant.SELECT_STOCK_ORG);
        }
    }

    /**
     * 设置库存类型
     */
    private void setDefStockType() {
        Date busDat = (Date) this.getModel().getValue(BillIdConstant.BUS_DATE);
        SimpleDateFormat dayFormat = new SimpleDateFormat("d");
        if (Integer.parseInt(dayFormat.format(busDat)) > NumConstant.DAYS) {
            getModel().setValue(BillIdConstant.STOCK_TYPE, StockTypeEnum.MARKET_SEC_HALF_MONTH.getCode());
        } else {
            getModel().setValue(BillIdConstant.STOCK_TYPE, StockTypeEnum.MARKET_FIRST_HALF_MONTH.getCode());
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {

    }


    /**
     * 校验组织
     * @return
     */
    public boolean verifyPass() {
        DynamicObject orgObj = (DynamicObject) this.getModel().getValue("yxgf_orgfield");
        if (orgObj != null && !StringUtils.isEmpty(orgObj.get("number").toString())) {
            return true;
        }
        return false;
    }


    /**
     * 校验信息
     * 产品是否选中
     * @return
     */
    public boolean verifyData(String billId, String verCol, int row) {
        DynamicObjectCollection collection = getModel().getEntryEntity(billId);
        if (collection != null && collection.size() > 0) {
            DynamicObject dynObj = (DynamicObject) this.getModel().getValue(verCol, row);
            if (dynObj != null && !StringUtils.isEmpty(dynObj.get("number").toString())) {
                return true;
            }
        }
        return false;
    }


    /**
     * 删除数据行
     *
     * @param formulaListen
     */
    private void delRowData(Boolean formulaListen) {
        if (formulaListen) {
            int rowIndex = this.getModel().getEntryCurrentRowIndex("yxgf_ent_product_formula");
            this.getModel().deleteEntryRow("yxgf_ent_product_formula", rowIndex);
        } else {
            int rowIndex = this.getModel().getEntryCurrentRowIndex("yxgf_ent_mprice_detail");
            this.getModel().deleteEntryRow("yxgf_ent_mprice_detail", rowIndex);
        }
    }

    /**
     * 构建产品明细
     */
    private void buildProDetail(String materialCode) {
        boolean isExist = false;
        DynamicObjectCollection collection = getModel().getEntryEntity(BillIdConstant.PRODUCT_DETAIL);
        if (collection != null && collection.size() > 1) {
            for (DynamicObject entry : collection) {
                if (StringUtils.equals(materialCode, entry.get("yxgf_product_code").toString())) {
                    isExist = true;
                    break;
                }
            }
        }
        if (!isExist) {
            QFilter qfilter = new QFilter("number", QCP.equals, materialCode);
            DynamicObject dynObj = QueryServiceHelper.queryOne("bd_material", "id,number,name,modelnum", qfilter.toArray());
            int index = this.getModel().createNewEntryRow(BillIdConstant.MAT_PRICE_DETAIL) - 1;
            getModel().setValue("yxgf_product_code", dynObj.get("number"), index);
            getModel().setValue("yxgf_product_name", dynObj.get("name"), index);
            getModel().setValue("yxgf_product_spec", dynObj.get("modelnum"), index);
        } else if (collection.size() > 1) {
            this.getModel().deleteEntryRow(BillIdConstant.PRODUCT_DETAIL, collection.size() - 1);
        }
    }

    private void calculate(String proCode) {

    }
}
